package com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeAccountBinding;

import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.base.FirstChangeAllBaseActivity;
import com.example.anew.journey.mynewjourney.base.MyApplication;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeAccountBinding.bean.QQbandingBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeAccountBinding.persenter.FirstChangeAccountBindingPersenter;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeAccountBinding.view.ISFirstChangeAccountBindingView;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeChangePhoneNumber.FirstChangeChangePhoneNumberActivity;
import com.example.anew.journey.mynewjourney.logic.login.LoginActivity;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司14
 * Created by 20433 on 2018/3/16
 */

public class FirstChangeAccountBindingActivity extends FirstChangeAllBaseActivity implements ISFirstChangeAccountBindingView {
    @Bind(R.id.activity_first_account_binding_tv_phone)
    TextView activityFirstAccountBindingTvPhone;
    @Bind(R.id.activity_first_account_binding_iv_phone_number_next_stop)
    ImageView activityFirstAccountBindingIvPhoneNumberNextStop;
    @Bind(R.id.activity_first_account_binding_tv_phone_number)
    TextView activityFirstAccountBindingTvPhoneNumber;
    @Bind(R.id.activity_first_account_binding_rl_phone_number)
    RelativeLayout activityFirstAccountBindingRlPhoneNumber;
    @Bind(R.id.activity_first_account_binding_tv_qq_binding)
    TextView activityFirstAccountBindingTvQqBinding;
    @Bind(R.id.activity_first_account_binding_tv_wechat_unbundling)
    TextView activityFirstAccountBindingTvWechatUnbundling;
    private View view;

    private FirstChangeAccountBindingPersenter mFirstChangeAccountBindingPersenter = new FirstChangeAccountBindingPersenter(this);


    /**
     * @desc 主要内容的布局资源填充进来
     */
    @Override
    protected View setMainContentView() {
        view = View.inflate(this, R.layout.activity_first_account_binding, null);
        ButterKnife.bind(this, view);
        return view;
    }

    /**
     * @desc 初始化数据 onCreate()
     */
    @Override
    protected void initView(View view) {
        displayToolbar();
        displayReturn();
        displayTvName();

        setToolbarBg(0xff2196F3);
        setReturnrePictuResources(R.mipmap.return_02);
        setTvNameEachAttribute(20, 0xffffffff, "账号绑定");
        mFirstChangeAccountBindingPersenter.initDate(this);
    }

    /**
     * @desc Activity 销毁 释放资源
     */
    @Override
    protected void releaseResources() {
        ButterKnife.unbind(view);
    }

    /**
     * @desc 网络监听 用于提示用户有网络了
     */
    @Override
    protected void promptHaveInternet() {

    }

    /**
     * @desc 网络监听 用于提示用户没有网络了
     */
    @Override
    protected void promptNoInternet() {

    }

    /**
     * @desc 点击分享按钮
     */
    @Override
    protected void onClickShared() {

    }

    /**
     * @desc 点击发布按钮
     */
    @Override
    protected void onClickRelease() {

    }

    /**
     * @desc 点击返回按钮
     */
    @Override
    protected void onClickReturn() {
        finish();
    }



    @OnClick({R.id.activity_first_account_binding_rl_phone_number, R.id.activity_first_account_binding_tv_qq_binding, R.id.activity_first_account_binding_tv_wechat_unbundling})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_first_account_binding_rl_phone_number:  //点击手机号
                mFirstChangeAccountBindingPersenter.onClickePhoneNumber();
                break;
            case R.id.activity_first_account_binding_tv_qq_binding:  // 点击qq 绑定
                mFirstChangeAccountBindingPersenter.onClickeQQBanding(this);

               // QQAccountBinding();
                break;
            case R.id.activity_first_account_binding_tv_wechat_unbundling:  //点击微信解绑
                mFirstChangeAccountBindingPersenter.onClickeWeChatUnbundling(this);
              //  WeChatAccountBinding();
                break;
        }
    }
    // 显示提示Toast信息
    @Override
    public void showToastInformation(String str) {
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
    // 点击跳转到 更换手机号页面
    @Override
    public void toChangePhoneNumberPager() {
        Intent intent =  new Intent(FirstChangeAccountBindingActivity.this, FirstChangeChangePhoneNumberActivity.class);
        startActivity(intent);
    }
    // 点击跳转到 登陆页面
    @Override
    public void toLoginPager() {
        Intent intent =  new Intent(FirstChangeAccountBindingActivity.this, LoginActivity.class);
        startActivity(intent);
    }
    // 显示进度
    @Override
    public void displayProgress() {

    }
    // 隐藏进度
    @Override
    public void hiddenProgress() {

    }
    //获取手机号
    @Override
    public String getPhoneNumber() {
        return activityFirstAccountBindingTvPhoneNumber.getText().toString().trim();
    }
    //设置手机号
    @Override
    public void setPhoneNumber(String str) {
        activityFirstAccountBindingTvPhoneNumber.setText(str);
    }
    //获取qq 绑定
    @Override
    public String getQQBanding() {
        return activityFirstAccountBindingTvQqBinding.getText().toString().trim();
    }
    //设置qq 绑定
    @Override
    public void setQQBanding(int textsize, String str, int textBgColor,int textColor) {
        activityFirstAccountBindingTvQqBinding.setText(str);
        activityFirstAccountBindingTvQqBinding.setTextSize(textsize);
        activityFirstAccountBindingTvQqBinding.setBackgroundResource(textBgColor);
        activityFirstAccountBindingTvQqBinding.setTextColor(textColor);
    }
    //获取 微信解绑
    @Override
    public String getWeChatUnbundling() {
        return activityFirstAccountBindingTvWechatUnbundling.getText().toString().trim();
    }
    //设置 微信解绑
    @Override
    public void setWeChatUnbundling(int textsize, String str, int textBgColor,int textColor) {
        activityFirstAccountBindingTvWechatUnbundling.setText(str);
        activityFirstAccountBindingTvWechatUnbundling.setTextSize(textsize);
        activityFirstAccountBindingTvWechatUnbundling.setBackgroundResource(textBgColor);
        activityFirstAccountBindingTvWechatUnbundling.setTextColor(textColor);
    }

    @Override
    public void QQAccountBinding() {
        Platform qzone = ShareSDK.getPlatform(QQ.NAME);
        if(qzone.isAuthValid()) {
            qzone.removeAccount(true);
        }
        qzone.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FirstChangeAccountBindingActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                arg0.getDb().exportData();
                final String  qQuserID = arg0.getDb().getUserId();

                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        String myuser_id =  mFirstChangeAccountBindingPersenter.getMyUserId(FirstChangeAccountBindingActivity.this);
                        banding(myuser_id,qQuserID);
                    }
                });

            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FirstChangeAccountBindingActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        qzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }



    @Override
    public void WeChatAccountBinding() {
        Platform Wachzone = ShareSDK.getPlatform(Wechat.NAME);
        if(Wachzone.isAuthValid()) {
            Wachzone.removeAccount(true);
        }
        Wachzone.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FirstChangeAccountBindingActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                final String   wechatUserId = arg0.getDb().getUserId();
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        String myuser_id =  mFirstChangeAccountBindingPersenter.getMyUserId(FirstChangeAccountBindingActivity.this);
                        bandingWeixin(myuser_id,wechatUserId);
                    }
                });

            }
            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                MyApplication.getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FirstChangeAccountBindingActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
//authorize与showUser单独调用一个即可
        Wachzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    }
    private void banding(String user_id, final String qq) {
        String url = RBConstants.SERVER_URL+RBConstants.ACCOUNT_BAINDING;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", user_id)
                .addParams("qq", qq)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        NLogger.e("TAG","========banding====NetworkResponseDate================="+NetworkResponseDate);
                        final QQbandingBean mQQbandingBean =  gson.fromJson(NetworkResponseDate, QQbandingBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(mQQbandingBean.errorCode == 200){
                                   String str =  activityFirstAccountBindingTvQqBinding.getText().toString().trim();
                                    SharedPreferences sharedPreferences = getSharedPreferences("My_App_Cardiac", MODE_PRIVATE);
                                    //得到SharedPreferences.Editor对象，并保存数据到该对象中
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    NLogger.e("TAG","=======并保存数据到该对象中========123===banding==========="+str);
                                    if(str.equals("绑定")){
                                       setQQBanding(16,"解绑", R.drawable.account_binding_tv_qq_unbinding,0xff666666);
                                        Toast.makeText(FirstChangeAccountBindingActivity.this, "qq 绑定成功", Toast.LENGTH_SHORT).show(); //绑定成功
                                        editor.putString("my_use_qq",qq);
                                    }else{
                                        setQQBanding(16,"绑定", R.drawable.account_binding_tv_qq_binding,0xff2196F3);
                                        Toast.makeText(FirstChangeAccountBindingActivity.this, "qq 解绑成功", Toast.LENGTH_SHORT).show();
                                        editor.putString("my_use_qq","");
                                    }
                                    //保存key-value对到文件中
                                    editor.commit();
                                }else{
                                    Toast.makeText(FirstChangeAccountBindingActivity.this, mQQbandingBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //   mISFirstChangeAccountBindingView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    private void bandingWeixin(String user_id, final String weixin) {
        String url = RBConstants.SERVER_URL+RBConstants.ACCOUNT_BAINDING;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", user_id)
                .addParams("weixin", weixin)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
//                         NLogger.e("TAG","=========bandingWeixin===NetworkResponseDate================="+NetworkResponseDate);
                        final QQbandingBean mQQbandingBean =  gson.fromJson(NetworkResponseDate, QQbandingBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(mQQbandingBean.errorCode == 200){
                                    String str =  activityFirstAccountBindingTvWechatUnbundling.getText().toString().trim();
                                    NLogger.e("TAG","=======并保存数据到该对象中========123===bandingWeixin==========="+str);
                                    SharedPreferences sharedPreferences = getSharedPreferences("My_App_Cardiac", MODE_PRIVATE);
                                    //得到SharedPreferences.Editor对象，并保存数据到该对象中
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    if(str.equals("绑定")){
                                        setWeChatUnbundling(16,"解绑", R.drawable.account_binding_tv_qq_unbinding,0xff666666);
                                        Toast.makeText(FirstChangeAccountBindingActivity.this, "微信 绑定成功", Toast.LENGTH_SHORT).show(); //微信 绑定成功
                                        editor.putString("my_use_weixin", weixin);
                                    }else{
                                        setWeChatUnbundling(16,"绑定", R.drawable.account_binding_tv_qq_binding,0xff2196F3);
                                        Toast.makeText(FirstChangeAccountBindingActivity.this, "微信 解绑成功", Toast.LENGTH_SHORT).show();
                                        editor.putString("my_use_weixin", "");
                                    }
                                    //保存key-value对到文件中
                                    editor.commit();
                                }else{
                                    Toast.makeText(FirstChangeAccountBindingActivity.this, mQQbandingBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //mISFirstChangeAccountBindingView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

}
